import datetime
from typing import Annotated
from fastapi import Depends, HTTPException
from sqlmodel import select

from app.users import models_help
from app.users import schema
from app.users.models import User
from app.users.models_help import update_user
from common.utils import SessionDep, create_token
from common.utils import ResponseDatas


# 登录接口
def login_access_token(session: SessionDep, form_data: Annotated[schema.OAuth2RequestForm, Depends()]):
    """
    # 官方使用的是
        from fastapi.security import OAuth2PasswordRequestForm
        form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
    # 在此 OAuth2RequestForm 为自定义的类对象
    OAuth2 compatible token login, get an access token for future requests
    """
    user = models_help.authenticate(
        session=session, account=form_data.username, password=form_data.password
    )
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect email or password")
    elif not user.is_active:
        raise HTTPException(status_code=400, detail="Inactive user")

    access_token=create_token(user)
    update_user(session, user, last_login=datetime.datetime.now())
    return schema.Token(access_token=access_token)


# 邮箱注册 (TODO 邮箱有效性验证)
def register_by_email(session: SessionDep, form_data: schema.SignUp):
    if not form_data.email:
        return ResponseDatas(status_code= 400, message="Please enter a valid email")

    existing_email = session.exec(select(User).where(User.email == form_data.email)).first()
    if existing_email:
        return ResponseDatas(status_code= 400, message="Email already registered")

    user_obj = models_help.create_user(session, name=form_data.name, password=form_data.password, email=form_data.email,
                                       is_active=False)
    return ResponseDatas(message="User created successfully")


# 电话注册 (TODO 电话有效性验证)
def register_by_phone(session: SessionDep, form_data: schema.SignUp):
    if form_data.phone:
        return ResponseDatas(status_code= 400, message="Please enter a valid phone")

    existing_phone = session.exec(select(User).where(User.phone == form_data.phone)).first()
    if existing_phone:
        return ResponseDatas(status_code=400, message="Phone already registered")

    user_obj = models_help.create_user(session, name=form_data.name, password=form_data.password, phone=form_data.phone,
                                       is_active=False)
    return ResponseDatas(message="User created successfully")